/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LOTTIEPRO_LOTTIE_CONFIG_DATA_BRIDGE_H
#define LOTTIEPRO_LOTTIE_CONFIG_DATA_BRIDGE_H

#include "dataManager/lottie_config_data.h"
#include "node/lottie_listener.h"
#include "common/napi_helper.h"
#include "dataManager/data_parse.h"
#include <rawfile/raw_file_manager.h>
#include <napi/native_api.h>
#include <string>

namespace LottiePro {

class LottieConfigBridge : public LottieConfig {
public:
    explicit LottieConfigBridge(napi_env env, napi_value);
    template <typename T>
    bool GetConfigValue(napi_value &jsObject, T &value, std::string const &parameter);
    bool GetResource(napi_value &jsObject, Resource &resource, std::string parameter);
    bool GetConfigLoopValue(napi_value &jsObject, std::variant<bool, int> &value,
                                        std::string const &parameter);
    bool GetResourceManager(napi_value &jsObject);
    template <typename T> T *GetObject(napi_value &jsObject);
    std::unique_ptr<LottieListener> &GetLottieListener();
    napi_threadsafe_function GetSafeFunction();

private:
    NapiHelper napiHelper_;
    bool Parse(napi_value value);
    bool ConvertToType(napi_value &napiValue, bool &boolValue);
    bool ConvertToType(napi_value &napiValue, std::string &stringValue);
    bool ConvertToType(napi_value &napiValue, int &intValue);
    bool ConvertToType(napi_value &napiValue, double &doubleValue);
    bool ConvertToType(napi_value &napiValue, AnimationSegment &animationSegment);
    bool ConvertToType(napi_value &napiValue, napi_value &jsObject);
    bool ConvertToType(napi_value &napiValue, Resource &resource);
    bool ConvertToType(napi_value &napiValue, ImageAssetDelegateType &imgAssets);
    std::unique_ptr<LottieListener> listener_{nullptr};
    napi_threadsafe_function safeFunc_{nullptr};
};

template <typename T>
bool LottieConfigBridge::GetConfigValue(napi_value &jsObject, T &value, std::string const &parameter)
{
    bool isExist = napiHelper_.CheckPropIsExist(jsObject, parameter);
    if (!isExist) {
        return false;
    }
    auto napiValue = napiHelper_.GetObjectProperty(jsObject, parameter);
    return ConvertToType(napiValue, value);
}

template <typename T> T *LottieConfigBridge::GetObject(napi_value &jsObject)
{
    return napiHelper_.UnwrapInstance<T>(jsObject);
}

} // namespace LottiePro

#endif
